<?php

if (!defined('IN_ACHAO_ORG'))
{
    trigger_error('Hacking attempt', E_USER_ERROR);
}

require_once(ROOT_PATH. '/includes/ctl.base.php');
//include_once(ROOT_PATH ."/UE/UE_Interface.php");

class ControllerFrontend extends ControllerBase
{
    /* private attributes */
    var $_log       = true;
    var $_log_item  = 0;
    var $_is_cached = false;
    var $_page_title = array();
    var $_allowed_actions = array();
    var $_page_type = MAIN_PAGE;
    var $dh = array();
    var $allCateList = array();
    var $cmsData = array();

    protected $_mall_category = array();

    var $_common_lang = array('common');

    var $_use_which_template = 'use_theme';

    var $_message_template_dir = 'mall';

    /* public functions */
    function __construct($act)
    {
        $this->ControllerFrontend($act);
    }

    /**

     * @author wj
     * @param string $act
     * @return void
     */
    function ControllerFrontend($act)
    {
        if (!in_array($act, $this->_allowed_actions))
        {
            $this->show_warning('Hacking Attempt');
            return;
        }
        if(!is_object($this->proxy))
        {
//            $this->proxy = new Proxy();
        }
        $class_name = get_class($this);
        //检查商城是否关闭
//        if ($this->conf('mall_maintain')==1)
        {
//        	$this->redirect(MAIN_DOMAIN."data/maintain.html");
//            return false;
        }
                
//        $this->dh = get_common_index();
//        $this->allCateList = getAllCateList();
//echo __FILE__.__LINE__;
        parent::ControllerBase($act);
    }

    /**
     * @brief set the type of page
     * @param $page_type must be MAIN_PAGE, STORE_PAGE, MY_APP_PAGE or RECOMMEND_PAGE
     * @see includes/inc.constant.php
     **/
    function set_page_type($page_type=MAIN_PAGE)
    {
       $this->_page_type = $page_type;
    }

    /**
     * 模板输出方法
     *
     * @author  wj
     * @param string  $template_file
     * @param string $template_dir    模板目录，如 mall 或者 store
     * @param string  $cache_id
     * @return  void
     */
    function display($template_file, $template_dir = '',$cache_id='')
    {
//echo __FILE__.__LINE__;
        $this->_init_template();
        if (empty($template_dir))
        {
            $template_dir = 'mall';
        }
//echo __FILE__.__LINE__;
        if (empty($this->_template->skin))
        {
            $skin_conf_key = $this->_template->store_id == 0 ? 'mall_skin' : 'store_skin';
//            $skin = $this->conf($skin_conf_key, $this->_template->store_id);

            $this->_template->skin = empty($skin) ? 'blue' : $skin;
        }
       // define('URL_REWRITE', $this->conf('mall_url_rewrite'));
//echo __FILE__.__LINE__;die();
        if (!empty($_SESSION['user_id']))
        {
            $this->assign('check_new_pm', 1);
        }

        //设置模板文件目录和编译文件目录
        $this->set_template_path('/' . $template_dir, '/' . $template_dir, TRUE);
//echo __FILE__.__LINE__;
        switch ($this->_page_type)
        {
        case MAIN_PAGE:
            $this->assign('is_main_page', 1);
            break;
        case STORE_PAGE:
            $this->assign('is_store_page', 1);
            break;
        case MY_APP_PAGE:
            $this->assign('is_my_app_page', 1);
            break;
        case RECOMMEND_PAGE:
            $this->assign('is_recommend_page', 1);
            break;
        default:
            $this->assign('is_main_page', 1);
            break;
        }
//echo __FILE__.__LINE__;

        $visitor = (isset($_SESSION['user_id']) && isset($_SESSION['user_name'])) ? $_SESSION['user_name'] : '';
        $this->assign('visitor',    $visitor);
       // $this->assign('client_download_url',    $this->conf("client_download_url"));

        $cart_goods_count = 0;
        $cart_goods_amount= 0;
        $cart_type_count  = 0;


        $this->assign('charset',        CHARSET);

//echo __FILE__.__LINE__;
            /*title*/
            $this->assign('title', $this->make_title());
//echo __FILE__.__LINE__;
            /* meta_keywords */
            $this->assign('meta_keywords', $this->get_meta_keywords());
            $this->assign('meta_description', $this->get_meta_description());
            $this->assign('lang',           $this->lang());
//echo __FILE__.__LINE__;
        
        
        $this->assign('keywordList', $keywordList);
        $headerKeyword = isset($this->_headerKeyword) ? $this->_headerKeyword : "";
        $this->assign('headerKeyword', $headerKeyword);
//echo __FILE__.__LINE__;
        $this->assign('file_url', FILE_URL);
         $this->assign('mallConfig', $this->_config);
//echo __FILE__.__LINE__;
        $this->assign('dh', $this->dh);

//        $this->assign('allCateList', dh_mapping($this->allCateList));
//echo __FILE__.__LINE__;
        parent::display($template_file, $cache_id);
    }

    function fetch($template_file, $cache_id = '')
    {

        $this->_init_template();
        if (empty($template_dir))
        {
            $template_dir = 'mall';
        }

        if (empty($this->_template->skin))
        {
            $skin_conf_key = $this->_template->store_id == 0 ? 'mall_skin' : 'store_skin';
            //$skin = $this->conf($skin_conf_key, $this->_template->store_id);

            $this->_template->skin = empty($skin) ? 'blue' : $skin;
        }
        define('URL_REWRITE', $this->conf('mall_url_rewrite'));

        if (!empty($_SESSION['user_id']))
        {
            $this->assign('check_new_pm', 1);
        }

        //设置模板文件目录和编译文件目录
        $this->set_template_path('/' . $template_dir, '/' . $template_dir, TRUE);

        switch ($this->_page_type)
        {
        case MAIN_PAGE:
            $this->assign('is_main_page', 1);
            break;
        case STORE_PAGE:
            $this->assign('is_store_page', 1);
            break;
        case MY_APP_PAGE:
            $this->assign('is_my_app_page', 1);
            break;
        case RECOMMEND_PAGE:
            $this->assign('is_recommend_page', 1);
            break;
        default:
            $this->assign('is_main_page', 1);
            break;
        }


        $visitor = (isset($_SESSION['user_id']) && isset($_SESSION['user_name'])) ? $_SESSION['user_name'] : '';
        $this->assign('visitor',    $visitor);
      //  $this->assign('client_download_url',    $this->conf("client_download_url"));

        $cart_goods_count = 0;
        $cart_goods_amount= 0;
        $cart_type_count  = 0;


        $this->assign('charset',        CHARSET);
        $this->assign('uc_path',        UC_API);
       // $this->assign('mall_copyright', $this->conf('mall_copyright'));
        $this->_assign_query_info();


        $category_base = $this->_mall_category;
        $this->assign('category', array_splice($category_base,1));
        $this->assign('category_one', $category_base);

            /*title*/
            $this->assign('title', $this->make_title());

            /* meta_keywords */
            $this->assign('meta_keywords', $this->get_meta_keywords());
            $this->assign('meta_description', $this->get_meta_description());
            $this->assign('lang',           $this->lang());



            /* send mail*/
            if (defined('SEND_MAIL'))
            {
                $send_mail_code = '<script type="text/javascript" src="index.php?app=mail&t=' . time()  . '" ></script>';
                $this->assign('send_mail_code', $send_mail_code);
            }

        /* 页头搜索条初始化 */
        //$key_words = array(array('type'=>'goods','keyword'=>'keyword'),array('type'=>'goods','keyword'=>'keyword22'));

   /*     $method = 'app.hotSearch';
        $postData =array('type'=>'app','startIndex'=>0,'maxNum'=>6);
        $keyval = array();
        $key_words = $this->manage->transDataFormList($postData,$keyval,$method,0,1,1);*/
  

        $keywordList = $this->_transformSearchkeywordList($key_words);

        $this->assign('keywordList', $keywordList);
        $headerKeyword = isset($this->_headerKeyword) ? $this->_headerKeyword : "";
        $this->assign('headerKeyword', $headerKeyword);


        //时间
  /*    $dArr = array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
        $d =date("w");
        $date =date("Y年m月d日");
        $this->assign('dispalyDate', $date." ".$dArr[$d]);*/

        
        $this->assign('dh', get_common_index());
 
        //赋值整个商场配置项  2010-10-16 dengxu
         $this->assign('mallConfig', $this->_config);
        
        $this->assign('lang', $this->lang());
        return parent::fetch($template_file, $cache_id);
    }

    /* private functions */
    /**
     *
     * @return  void
     */
    function config_template()
    {
        parent::config_template();

        $this->_template->cache_dir = ROOT_PATH . '/temp/caches';
        $this->_template->template_dir  = ROOT_PATH . '/themes';
        $this->_template->compile_dir   = ROOT_PATH . '/temp/compiled';
        $this->_template->cache_lifetime = 10;//$this->conf('mall_cache_life'); 
    }


    /**
     * 
     *
     * @param string    $cache_id   
     * @return boolen
     */
    function is_cached($cache_id)
    {
        #### 静态化统一做，不用template组件的静态化页面生成功能 modified by caiyizhen ####
        return false;
        /*
        if (DEBUG_MODE & 1 == 1 || isset($_GET['edit_mode']))
        {
            return false;
        }
        else
        {
            $this->_init_template();
            $this->_template->appoint_cache_id = true;
            $cache_dir = $this->cache_dir($cache_id);

            if (is_dir(ROOT_PATH . '/temp/caches' . $cache_dir) ||
                ecm_mkdir('/temp/caches' . $cache_dir))
            {
                //����Ŀ¼�ɹ����������û���Ŀ¼
                $this->_template->cache_dir = ROOT_PATH . '/temp/caches' . $cache_dir ;
            }

            if ($this->_template->is_cached('',$cache_id))
            {
                $this->_is_cached = true;
            }

            return $this->_is_cached;
        }
        */
    }

    /**
     * 
     *
     * @author wj
     * @param string    $cache_id   
     * @return string   
     */
    function cache_dir($cache_id)
    {
        $cache_path = md5($cache_id);
        $cache_path = '/' . $cache_path{0} . $cache_path{1} . '/' . $cache_path{2} . $cache_path{3} ;

        return $cache_path;
    }

    /**
     *ֵ
     *
     * @param var  $param
     * @return string
     *      */
    function crc32_code($param)
    {
        ksort($param);

        return sprintf("%x", crc32(var_export($param, true)));
    }

    /**

     *
     * @param   string  $key
     *
     * @return  string|array
     */
    function lang($key = '')
    {
        if (!Language::is_loaded($this->_common_lang))
        {

            $this->_load_common_lang();
        }

        return parent::lang($key);
    }

    /**
     *
     * @athor   weberliu
     * @param   void
     * @return  string
     */
    function make_title()
    {

        $metaTitle = '';//$this->conf('mall_title');
        return isset($this->_appName) ? $this->_appName. ($this->_stripMetaTitle ? '' : ' - '.$metaTitle) : $metaTitle;
        //return implode('-', $this->_page_title);
    }

    /**
     * 
     * @param array
     *
     * @return void
     */
    function set_title($meta)
    {
        $this->_page_title = $meta;
    }

    /**
     *
     *
     * @author  scottye
     *
     * @param   int     $store_id
     * @return  void
     */
    function update_pageview($store_id = 0)
    {
        if (is_from_browser())
        {
            include_once(ROOT_PATH . '/includes/manager/mng.pageview.php');
            $mng_pageview = new PageviewManager($store_id);
            $mng_pageview->update_pageview();
        }
    }

    /**
     * 获取网站网站关键字: 
     *
     * @author  wj
     * @param void
     * @return string
     */
    function get_meta_keywords()
    {
      
        $keywords = '';//$this->conf('mall_keywords');
        
        if (empty($keywords))
        {
            $keywords = 'zyw';
        }

        return $keywords;
    }

    
   /**
     * 获取网站网站间接: 
     *
     * @author  dengxu 2010-10-16
     * @param void
     * @return string
     */
    function get_meta_description()
    {
        
        $description = '';//$this->conf('mall_description');
        

        if (empty($description))
        {
            $description = 'zyw组成';
        }

        return $description;
    }
    
    function getCache()
    {
        if($this->cache == null)
        {
            $this->cache = UE_Cache::getInstance(DB_CACHE_TYPE);
        }
        return $this->cache;
    }

    /**
     * 组装搜索关键字排行列表
     *
     * @param array list
     */
    private function _transformSearchkeywordList($list,$type='good')
    {
        if(is_array($list))
        {
            foreach ($list as &$keyword)
            {
                switch ($type)
                {
                    case 'good':
                    case 'goods':
                        $keyword['url'] = 'index.php?app=search&keywords='.urlencode($keyword['keyword']);
                        break;
                    case 'user':
                        $keyword['url'] = 'index.php?app=search&act=user&keywords='.urlencode($keyword['keyword']);
                        break;
                    case 'store':
                        $keyword['url'] = 'index.php?app=search&act=shop&keywords='.urlencode($keyword['keyword']);
                        break;
                }
            }
        }
        return $list;
    }

    /**
     * 截断字符串
     *
     * @author caiyizhen
     * @param string $str 要截断的字符串
     * @param int 最大长度
     * @param string $suffix 截断后添加的后缀，默认三个点
     * @param boolean $haveHtmlEntities 是否有html标签
     * @return string
     */
    protected function _cutStr($str,$maxLength=10,$suffix = '...',$haveHtmlEntities = false)
    {
        $length = mb_strlen($str);
        if ($maxLength>$length*2) {
            return $str;
        }
        $preStr = '';
        $subStr = $str;
        $count = 0;
        $outOfTag = true;

        for($pos = 0;$pos<$length;$pos++)
        {
            $char = mb_substr($subStr,0,1,'utf-8');
            $preStr .= $char;

            if ($char=='<' && $haveHtmlEntities) $outOfTag = false;
            if ($outOfTag) {
                if (preg_match('/[\x{4e00}-\x{9fa5}]/u',$char)) {
                    $count = $count + 2;
                }
                if (preg_match('/[0-9A-Za-z]/u',$char)) {
                    $count++;
                }
            }
            if ($count > $maxLength*2){
                return $preStr.$suffix;
            }
            if ($char=='>' && $haveHtmlEntities) $outOfTag = true;
            $subStr = mb_substr($subStr,1,$length,'utf-8');
        }
        return $preStr.$suffix;
    }
    
	/**
     * 显示专题模板视图
     * @author niejianyou
     */
    function display_special_templet($filename,$public=true)
    {
        $this->_init_special_view();
        if($public)
        {
            $this->_view->template_dir  = ROOT_PATH;
            $this->_view->compile_dir  = ROOT_PATH.'/temp/compiled/mall';
        }
        $this->_assign_query_info();
        $this->_view->display($filename);
    }    
    
	function _init_special_view()
    {
        if ($this->_view === null)
        {	
        	include(ROOT_PATH . '/includes/cls.template.php');
            $this->_view = new ecsTemplate();
            $this->_config_special_view();  //配置
        }
    }
    
	function assign_special($k, $v = null)
    {
        $this->_init_special_view();
        if (is_array($k))
        {
            $args  = func_get_args();
            foreach ($args as $arg)     //遍历参数
            {
                foreach ($arg as $key => $value)    //遍历数据并传给视图
                {
                    $this->_view->assign($key, $value);
                }
            }
        }
        else
        {
            $this->_view->assign($k, $v);
        }
    }

    /**
     *    配置视图
     *
     *    @return    void
     */
    function _config_special_view()
    {
        $this->_view->caching       = ((DEBUG_MODE & 1) == 0);  // 是否缓存
        $this->_view->force_compile = ((DEBUG_MODE & 2) == 2);  // 是否需要强制编译
        $this->_view->direct_output = ((DEBUG_MODE & 4) == 4);  // 是否直接输出
        $this->_view->gzip          = (defined('ENABLED_GZIP') && ENABLED_GZIP === 1);
    }
    

    /**
     *    检查登陆
     *
     *    @return    void
     */
    function check_login($isAjax=0)
    {
        if(!$_SESSION['user_id'])
        {
        	if($isAjax)
        	{
        		die(json_encode(array('error'=>100,'msg'=>'您没有登陆，不能进行此操作')));
        	}
        	else 
        	{
        		$this->show_message('您没有登陆，不能进行此操作');
        	}
        }
    }
};

class MessageBase extends ControllerFrontend {};

